package com.beidasoft.flip.webframe.core.configuration;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;

import com.beidasoft.flip.webframe.core.consts.CacheConsts;
import com.beidasoft.flip.webframe.core.pojo.FieldsMapping;

/**
 * <p>自动化配置的初始化类</p>
 * @author 肖翔
 * @date 2019/12/04
 */
@Component
public class AutoConfiguration implements ApplicationListener<ContextRefreshedEvent> {

    /**
     * 读取配置文件里面加入的yml文件的名称
     */
    @Value("${fieldsmapping}")
    private String fieldsmapping;

    /**
     * yml文件的根节点名称
     */
    @Value("${rootname}")
    private String rootName;

    /**
     * 注入多个yaml文件
    *
     */
    @SuppressWarnings("unchecked")
    private void fieldsmapping() {
        InputStream reader = getYMLInputStream(fieldsmapping);
        Map<String, Map<String, Map<String, String>>> map = (Map<String, Map<String, Map<String, String>>>)new Yaml()// 构造一个新的yaml对象
            .loadAs(reader, Map.class)// 获取数据转化为map
            .get(rootName);// 获取根节点下面的数据
        FieldsMapping mapping = new FieldsMapping();//构造一个对象
        map.forEach((targetClass, sourceMap) -> {
            mapping.setTargetClass(targetClass);//输入目标类的名称
            sourceMap.forEach((sourceClass, fieldsMap) -> {
                mapping.setSourceClass(sourceClass);//输入源类的名称
                mapping.add(fieldsMap);//把对应字段的映射关系设置进去
            });

            //如果不为默认配置的话，进行字段的逆向存储，可以避免重复配置
            mapping.setSourceClass(targetClass);
            sourceMap.forEach((sourceClass, fieldsMap) -> {
                if (!sourceClass.equalsIgnoreCase("default")) {
                    mapping.setTargetClass(sourceClass);
                    final Map<String, String> tmpMap = new HashMap<>();
                    fieldsMap.forEach((k, v) -> {
                        tmpMap.put(v, k);
                    });
                    mapping.add(tmpMap);
                }
            });
        });
        CacheConsts.fieldsMapping = mapping;//处理初始化结果集
    }

    private InputStream getYMLInputStream(String fileName) {
        return this.getClass().getClassLoader().getResourceAsStream(fileName);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        fieldsmapping();
    }

}
